//
//  UISegmentedControl+versionStyle.m
//  FCPackage
//
//  Created by fly on 2020/1/9.
//

#import "UISegmentedControl+versionStyle.h"

@implementation UISegmentedControl (versionStyle)

/** UISegmentedControl 将iOS13风格转化成iOS12之前的风格样式 */
- (void)ensureiOS12Style
{
    if (@available(iOS 13, *)) {
           UIColor *tintColor = [self tintColor];
           UIImage *tintColorImage = [self imageWithColor:tintColor];
        
           [self setBackgroundImage:[self imageWithColor:self.backgroundColor ? self.backgroundColor : [UIColor clearColor]] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
           [self setBackgroundImage:tintColorImage forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];
           [self setBackgroundImage:[self imageWithColor:[tintColor colorWithAlphaComponent:0.2]] forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
           [self setBackgroundImage:tintColorImage forState:UIControlStateSelected|UIControlStateSelected barMetrics:UIBarMetricsDefault];
           [self setTitleTextAttributes:@{NSForegroundColorAttributeName:tintColor, NSFontAttributeName: [UIFont systemFontOfSize:13]} forState:UIControlStateNormal];
           [self setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName: [UIFont systemFontOfSize:13]} forState:UIControlStateSelected];
           [self setDividerImage:tintColorImage forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
           self.layer.masksToBounds = YES;
           self.layer.borderWidth = 1;
           self.layer.borderColor = [tintColor CGColor];
       }
}

- (UIImage *)imageWithColor: (UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}
@end
